//
//  PrintWebViewController.m
//  ShoppingExperience
//
//  Created by LiYinDi on 15/9/30.
//  Copyright (c) 2015年 RuiBen. All rights reserved.
//

#import "PrintWebViewController.h"
#import "APLPrintPageRenderer.h"
@interface PrintWebViewController ()<UIPrintInteractionControllerDelegate>

@end

@implementation PrintWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
  
    //[btn setTitle:@"ZoomIn" forState:UIControlStateHighlighted];
    //[btn addTarget:self action:@selector(zoomInAction:) forControlEvents:UIControlEventTouchUpInside];
    //self.navigationBar.hidden=NO;
    [_leftArrowBtn addTarget:self action:@selector(leftArrowBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_righttArrowBtn addTarget:self action:@selector(rightArrowBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_printBtn addTarget:self action:@selector(printBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self requestPrintWebURL:@"1"];
}
-(void)leftArrowBtnClick
{
    if ([_leftNumLabel.text intValue]>1) {
        _leftNumLabel.text=[NSString stringWithFormat:@"%d",[_leftNumLabel.text intValue]-1];
         [self requestPrintWebURL:_leftNumLabel.text];
    }
}
-(void)rightArrowBtnClick
{
    if ([_leftNumLabel.text intValue]<[_rightNumLabel.text intValue]) {
        _leftNumLabel.text=[NSString stringWithFormat:@"%d",[_leftNumLabel.text intValue]+1];
         [self requestPrintWebURL:_leftNumLabel.text];
    }

}
-(void)requestPrintWebURL:(NSString *)pageIndexStr
{
    if ([Global getLoginToken].length>0) {
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        NSMutableDictionary *params=[[NSMutableDictionary alloc] init];
        [params setObject:[Global getLoginToken] forKey:@"Token"];
        [params setObject:_docTypeStr forKey:@"DocType"];
        [params setObject:_docNumStr forKey:@"DocNum"];
        [params setObject:_docStatusStr forKey:@"DocStatus"];
        [params setObject:@"iOSPad" forKey:@"sSystemName"];
        [params setObject:pageIndexStr forKey:@"PageIndex"];
       //NSLog(@"PA===%@",params);
        [HttpRequest requestData:@"Common/GetDocPrintUrl" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                   // NSLog(@"sss====%@",severDataDict.dataDict);
                    NSString *totalPageStr=[NSString stringWithFormat:@"%d",[[severDataDict.dataDict objectForKey:@"TotalCount"] intValue]];
                    _rightNumLabel.text=totalPageStr;
                    if ([severDataDict.dataDict objectForKey:@"Url"]!=[NSNull null]&&[[severDataDict.dataDict objectForKey:@"Url"] length]>0) {
                         NSString *urlStr=[severDataDict.dataDict objectForKey:@"Url"];
                   //     NSLog(@"urlStr====%@",urlStr);
                        [_printWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
                        
                    }
                    if(![UIPrintInteractionController isPrintingAvailable]){
                        _printButton.enabled = NO;
                    }
                   
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                    //  [Global showTextHud:requestResultStr view:self.view];
                    [Global showTextHudSub:requestResultStr view:self.view];
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                        
                        [Global loginViewController:self noteStr:requestResultStr];
                        ///  [Global loginViewController:self];
                    }
                    
                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
        }];
        
    }

}
-(IBAction)printBackClick:(id)sender
{
    //[self.navigationController popViewControllerAnimated:YES];
    if (self.view!=nil) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        
    }
//    if ([self.delegate respondsToSelector:@selector(PrintWebBackClick)]) {
//        [self.delegate PrintWebBackClick];
//    }
}
-(void)printBtnClick
{
    UIPrintInteractionController *controller = [UIPrintInteractionController sharedPrintController];
    
    controller.delegate=self;
    //controller.printFormatter set
    if(!controller){
        NSLog(@"Couldn't get shared UIPrintInteractionController!");
        return;
    }
    
    UIPrintInteractionCompletionHandler completionHandler =
    ^(UIPrintInteractionController *printController, BOOL completed, NSError *error) {
        if(!completed && error){
            NSLog(@"FAILED! due to error in domain %@ with error code %ld", error.domain, (long)error.code);
        }
    };
    
    
    // Obtain a printInfo so that we can set our printing defaults.
    UIPrintInfo *printInfo = [UIPrintInfo printInfo];
    // This application produces General content that contains color.
    printInfo.outputType =UIPrintInfoOutputGrayscale;// UIPrintInfoOutputGeneral;
    // We'll use the URL as the job name.
    printInfo.jobName = @"";
   
    // Set duplex so that it is available if the printer supports it. We are
    // performing portrait printing so we want to duplex along the long edge.
    printInfo.duplex =UIPrintInfoDuplexNone;// UIPrintInfoDuplexLongEdge;
    printInfo.orientation=UIPrintInfoOrientationLandscape;
    // Use this printInfo for this print job.
    controller.printInfo = printInfo;
    
    // Be sure the page range controls are present for documents of > 1 page.
    controller.showsPageRange = NO;
    
    
    // This code uses a custom UIPrintPageRenderer so that it can draw a header and footer.
    APLPrintPageRenderer *myRenderer = [[APLPrintPageRenderer alloc] init];
    // The APLPrintPageRenderer class provides a jobtitle that it will label each page with.
    myRenderer.jobTitle = printInfo.jobName;
    
    // To draw the content of each page, a UIViewPrintFormatter is used.
    UIViewPrintFormatter *viewFormatter = [_printWebView viewPrintFormatter];
    
    
    controller.printFormatter = viewFormatter;
    
#if SIMPLE_LAYOUT
    /*
     For the simple layout we simply set the header and footer height to the height of the
     text box containing the text content, plus some padding.
     
     To do a layout that takes into account the paper size, we need to do that
     at a point where we know that size. The numberOfPages method of the UIPrintPageRenderer
     gets the paper size and can perform any calculations related to deciding header and
     footer size based on the paper size. We'll do that when we aren't doing the simple
     layout.
     */
   // UIFont *font = [UIFont fontWithName:@"Helvetica" size:HEADER_FOOTER_TEXT_HEIGHT];
    //CGSize titleSize = [myRenderer.jobTitle sizeWithFont:font];
   // myRenderer.headerHeight = myRenderer.footerHeight = titleSize.height + HEADER_FOOTER_MARGIN_PADDING;
#endif
    [myRenderer addPrintFormatter:viewFormatter startingAtPageAtIndex:0];
    // Set our custom renderer as the printPageRenderer for the print job.
    
    controller.printPageRenderer = myRenderer;
    
    /*
     The method we use to present the printing UI depends on the type of UI idiom that is currently executing. Once we invoke one of these methods to present the printing UI, our application's direct involvement in printing is complete. Our custom printPageRenderer will have its methods invoked at the appropriate time by UIKit.
     */
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
       //  UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:_printBtn];
        
        [controller presentFromBarButtonItem:_printButton animated:YES completionHandler:completionHandler];  // iPad
    }
    else {
        [controller presentAnimated:YES completionHandler:completionHandler];  // iPhone
    }
    
}
- (UIPrintPaper *)printInteractionController:(UIPrintInteractionController *)printInteractionController choosePaper:(NSArray *)paperList
{
  
    CGSize paperSize = CGSizeMake(595, 880);
    return [UIPrintPaper bestPaperForPageSize:paperSize withPapersFromArray:paperList];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
